var date = new Date;
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var phoneWith = window.innerWidth;
var phoneHeight = window.innerHeight;
var phoneNum = 4;//每屏显示个数。

require([
    'require',
    'chart'
], function (require) {
    require(['chart', 'ionic'], function (ec) {
        angular.module('starter', ['ionic'])
            .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
                $stateProvider
                    .state('tab', {
                        url: "/tab",
                        templateUrl: "templates/tabs.html",
                        controller: 'tabCtrl'
                    });
                $urlRouterProvider.otherwise('/tab');

                $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            })
            .factory('DataService', ['$q', '$http', '$ionicLoading', function ($q, $http, $ionicLoading) {
                var result = {},
                    activeType = 'SO',
                    name = {
                        SO: [{name: '订货金额'}],
                        Ship: [{name: '出货金额'}],
                        SDReceiveDetail: [{name: '收款金额'}],
                        SDARConfirmDetail: [{name: '立账金额'}]
                    },
                    localData = {
                        SO: {},
                        Ship: {},
                        SDReceiveDetail: {},
                        SDARConfirmDetail: {}
                    },
                    currentDatas = {
                        SO: [],
                        Ship: [],
                        SDReceiveDetail: [],
                        SDARConfirmDetail: []
                    },
                    pieTitle = {
                        SO: '产品分类(' + year + '/' + month + ')',
                        Ship: '产品分类(' + year + '/' + month + ')',
                        SDReceiveDetail: '产品分类(' + year + '/' + month + ')',
                        SDARConfirmDetail: '产品分类(' + year + '/' + month + ')'
                    },
                    localTimer = {
                        SO: {year: year, month: month},
                        Ship: {year: year, month: month},
                        SDReceiveDetail: {year: year, month: month},
                        SDARConfirmDetail: {year: year, month: month}
                    },
                    ms = 0;
                result.loadData = function (begin, end, type) {
                    var defer = $q.defer();
                    var OrgCode = u9.getLoginData().OrgCode,
                        CountedPeriod = "month",
                        BeginTime = begin.year + '-' + begin.month + '-' + '01' + ' 00:00:00',
                        EndTime = end.year + '-' + (end.month + 1) + '-' + '01' + ' 00:00:00',
                        QueryType = type;
                    if (end.month == 12) {
                        EndTime = (end.year + 1) + '-' + 1 + '-' + '01' + ' 00:00:00'
                    }
                    u9.callSV({
                        name: 'UFIDA.U9.ISV.SM.IQueryTotalMoneySV',
                        params: [OrgCode, CountedPeriod, BeginTime, EndTime, QueryType],
                        onSuccess: function (data) {
                            angular.forEach(data, function (obj) {
                                if (!localData[QueryType][obj.Year]) {
                                    localData[QueryType][obj.Year] = {};
                                }
                                if (!localData[QueryType][obj.Year][obj.Month]) {
                                    localData[QueryType][obj.Year][obj.Month] = obj;
                                }

                            });
                            defer.resolve();
                        },
                        onFailure: function (err) {
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    });
                    return defer.promise;
                };
                function getTimer(timer, distance) {
                    var initStart = {
                        year: 0,
                        month: 0
                    }, initEnd = {
                        year: 0,
                        month: 0
                    };

                    if (timer.month >= distance) {
                        initStart.year = timer.year;
                        initStart.month = timer.month - distance + 1;
                    } else {
                        initStart.year = timer.year - 1;
                        initStart.month = 12 - (distance - timer.month) + 1;
                    }
                    initEnd.year = timer.year;
                    initEnd.month = timer.month;
                    return {
                        initStart: initStart,
                        initEnd: initEnd
                    }
                }

                function initInfo() {
                    var info = {
                        Month: 0,
                        Quarter: 0,
                        QueryDetailInfo: [
                            {
                                Money: 0,
                                QueryResult: null,
                                SaleCategory: "这个时间段没有销售额"
                            }],
                        TotalMoney: 0,
                        Week: 0,
                        Year: 0
                    };
                    return info;
                }

                result.initData = function (timer, type) {
                    var defer = $q.defer();
                    var localTime = getTimer(timer, phoneNum);
                    var beginDate = new Date();
                    if (currentDatas[type].length > 0) {
                        defer.resolve({
                            currentData: currentDatas[type],
                            time: timer,
                            beginDate: beginDate
                        });
                    } else {
                        result.loadData(localTime.initStart, localTime.initEnd, type).then(function () {
                            if (localData[type]) {
                                if ((localTime.initEnd.year == localTime.initStart.year) && (localTime.initEnd.month >= phoneNum)) {
                                    for (var i = 0; i < phoneNum; i++) {
                                        if (!localData[type][localTime.initEnd.year][localTime.initEnd.month - phoneNum + i + 1]) {
                                            var info = initInfo();
                                            info.Month = localTime.initEnd.month - phoneNum + i + 1;
                                            info.Year = localTime.initEnd.year;
                                            currentDatas[type].push(info)
                                        } else {
                                            currentDatas[type].push(localData[type][localTime.initEnd.year][localTime.initEnd.month - phoneNum + i + 1]);

                                        }
                                    }
                                } else {
                                    for (var i = 0; i < phoneNum - localTime.initEnd.month; i++) {
                                        if ((!localData[type][localTime.initStart.year]) || (!localData[type][localTime.initStart.year][13 - phoneNum + localTime.initEnd.month + i])) {
                                            var info = initInfo();
                                            info.Month = 13 - phoneNum + localTime.initEnd.month + i;
                                            info.Year = localTime.initStart.year;
                                            currentDatas[type].push(info)
                                        } else {
                                            currentDatas[type].push(localData[type][localTime.initStart.year][13 - phoneNum + localTime.initEnd.month + i]);
                                        }
                                    }
                                    for (var i = localTime.initEnd.month; i > 0; i--) {
                                        if ((!localData[type][localTime.initEnd.year]) || (!localData[type][localTime.initEnd.year][localTime.initEnd.month - i + 1])) {
                                            var info = initInfo();
                                            info.Month = localTime.initEnd.month - i + 1;
                                            info.Year = localTime.initEnd.year;
                                            currentDatas[type].push(info)
                                        } else {
                                            currentDatas[type].push(localData[type][localTime.initEnd.year][localTime.initEnd.month - i + 1]);
                                        }
                                    }
                                }
                                defer.resolve({
                                    currentData: currentDatas[type],
                                    time: timer,
                                    beginDate: beginDate
                                });
                            } else {
                                alert("无此时间段数据!");
                                defer.reject(false);
                            }
                        }, function () {
                            alert("调取服务失败！");
                            defer.reject(false);
                        });
                    }

                    return defer.promise;
                };
                result.setActiveType = function (type) {
                    activeType = type;
                };
                result.getActiveType = function () {
                    return activeType;
                };
                result.getName = function (type) {
                    return name[type][0];
                };
                result.setTitle = function (type, name) {
                    pieTitle[type] = '产品分类(' + name + ')';
                };
                result.getTitle = function (type) {
                    return pieTitle[type];
                };
                result.refreshData = function (direction, timer, type) {
                    var defer = $q.defer();
                    ms = 0;
                    var beginDate = new Date();
                    var distance = 2;//初始化滑动距离为1
                    if (direction == -1) {
                        var leftTimerQeq = angular.copy(timer),
                            leftTimerQes = angular.copy(timer),
                            pointerTime = angular.copy(timer);
                        var promises = [];
                        var nextLeftPointerTime = {};
                        for (var i = 1; i <= distance; i++) {
                            if (leftTimerQeq.month - phoneNum > 0) {
                                nextLeftPointerTime.year = leftTimerQeq.year;
                                nextLeftPointerTime.month = leftTimerQeq.month - phoneNum;
                            } else {
                                nextLeftPointerTime.year = leftTimerQeq.year - 1;
                                nextLeftPointerTime.month = 12 - (phoneNum - leftTimerQeq.month);
                            }
                            if ((!localData[type][nextLeftPointerTime.year]) || (!localData[type][nextLeftPointerTime.year][nextLeftPointerTime.month])) {
                                promises.push(result.loadData(nextLeftPointerTime, nextLeftPointerTime, type));
                            } else {
                                currentDatas[type].pop();
                                currentDatas[type].unshift(localData[type][nextLeftPointerTime.year][nextLeftPointerTime.month]);
                            }

                            if (leftTimerQeq.month != 1) {
                                leftTimerQeq.month = leftTimerQeq.month - 1;
                            } else {
                                leftTimerQeq.year -= 1;
                                leftTimerQeq.month = 12;
                            }
                        }
                        if (promises.length > 0) {
                            $q.all(promises).then(function () {
                                var nextLeftPointerTime = {};
                                for (var i = 1; i <= distance; i++) {
                                    if (leftTimerQes.month - phoneNum > 0) {
                                        nextLeftPointerTime.year = leftTimerQes.year;
                                        nextLeftPointerTime.month = leftTimerQes.month - phoneNum;
                                    } else {
                                        nextLeftPointerTime.year = leftTimerQes.year - 1;
                                        nextLeftPointerTime.month = 12 - (phoneNum - leftTimerQes.month);
                                    }

                                    if ((!localData[type][nextLeftPointerTime.year]) || (!localData[type][nextLeftPointerTime.year][nextLeftPointerTime.month])) {
                                        var info = initInfo();
                                        info.Month = nextLeftPointerTime.month;
                                        info.Year = nextLeftPointerTime.year;
                                        currentDatas[type].pop();
                                        currentDatas[type].unshift(info);
                                    } else {
                                        currentDatas[type].pop();
                                        currentDatas[type].unshift(localData[type][nextLeftPointerTime.year][nextLeftPointerTime.month]);
                                    }

                                    if (leftTimerQes.month != 1) {
                                        leftTimerQes.month = leftTimerQes.month - 1;
                                    } else {
                                        leftTimerQes.year -= 1;
                                        leftTimerQes.month = 12;
                                    }
                                }

                                if (timer.month > distance) {
                                    pointerTime.month = timer.month - distance;
                                } else {
                                    pointerTime.year = timer.year - 1;
                                    pointerTime.month = 12 + timer.month - distance;
                                }

                                defer.resolve({
                                    currentData: currentDatas[type],
                                    time: pointerTime,
                                    beginDate: beginDate
                                });
                            });
                        } else {
                            if (timer.month > distance) {
                                pointerTime.month = timer.month - distance;
                            } else {
                                pointerTime.year = timer.year - 1;
                                pointerTime.month = 12 + timer.month - distance;
                            }
                            defer.resolve({
                                currentData: currentDatas[type],
                                time: pointerTime,
                                beginDate: beginDate
                            });
                        }
                    }
                    else if (direction == 1) {
                        var reallyDistance = 0;
                        var rightTimerQeq = angular.copy(timer),
                            pointerTime = angular.copy(timer),
                            nextRightPointerTime = {};

                        for (var i = 1; i <= distance; i++) {
                            if (rightTimerQeq.month == 12) {
                                nextRightPointerTime.year = rightTimerQeq.year + 1;
                                nextRightPointerTime.month = 1;
                            } else {
                                nextRightPointerTime.year = rightTimerQeq.year;
                                nextRightPointerTime.month = rightTimerQeq.month + 1;
                            }

                            if (nextRightPointerTime.year <= beginDate.getFullYear()) {
                                if ((!localData[type][nextRightPointerTime.year]) || (!localData[type][nextRightPointerTime.year][nextRightPointerTime.month])) {
                                    var info = initInfo();
                                    info.Month = nextRightPointerTime.month;
                                    info.Year = nextRightPointerTime.year;
                                    currentDatas[type].shift();
                                    currentDatas[type].push(info);
                                } else {
                                    currentDatas[type].shift();
                                    currentDatas[type].push(localData[type][nextRightPointerTime.year][nextRightPointerTime.month]);
                                }
                                if (rightTimerQeq.month == 12) {
                                    rightTimerQeq.year = rightTimerQeq.year + 1;
                                    rightTimerQeq.month = 1;
                                } else {
                                    rightTimerQeq.month = rightTimerQeq.month + 1;
                                }
                                //实际需要移动距离
                                reallyDistance++;
                            }
                        }

                        if (12 - timer.month >= reallyDistance) {
                            pointerTime.month = timer.month + reallyDistance;
                        } else {
                            pointerTime.year = timer.year + 1;
                            pointerTime.month = timer.month + reallyDistance - 12;
                        }

                        defer.resolve({
                            currentData: currentDatas[type],
                            time: pointerTime,
                            beginDate: beginDate
                        });
                    }
                    return defer.promise;
                };

                result.getMs = function () {
                    return ms;
                };
                result.setMs = function (value) {
                    ms = value;
                };
                result.getLocalTimer = function (type) {
                    return localTimer[type];
                };
                result.setLocalTimer = function (type, value) {
                    localTimer[type] = value;
                };
                return result;
            }
            ])
            .
            factory('shareCombobox', [
                '$rootScope',
                '$document',
                '$compile',
                '$animate',
                '$timeout',
                '$ionicTemplateLoader',
                '$ionicPlatform',
                function ($rootScope, $document, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform) {

                    return {
                        show: actionSheet
                    };

                    function actionSheet(opts) {
                        var scope = $rootScope.$new(true);

                        angular.extend(scope, {
                            cancel: angular.noop,
                            data: [],
                            displayField: 'name',
                            valueField: 'id',
                            buttonClicked: angular.noop,
                            $deregisterBackButton: angular.noop,
                            cancelOnStateChange: true
                        }, opts || {});

                        // Compile the template
                        var element = scope.element = $compile('<share-combobox ng-class="cssClass"></share-combobox>')(scope);

                        // Grab the sheet element for animation
                        var sheetEl = angular.element(element[0].querySelector('.action-sheet-wrapper'));

                        var stateChangeListenDone = scope.cancelOnStateChange ?
                            $rootScope.$on('$stateChangeSuccess', function () {
                                scope.cancel();
                            }) :
                            angular.noop;

                        // removes the actionSheet from the screen
                        scope.removeSheet = function (done) {
                            if (scope.removed) return;

                            scope.removed = true;
                            sheetEl.removeClass('action-sheet-up');
                            $document[0].body.classList.remove('action-sheet-open');
                            scope.$deregisterBackButton();
                            stateChangeListenDone();

                            $animate.removeClass(element, 'active').then(function () {
                                scope.$destroy();
                                element.remove();
                                // scope.cancel.$scope is defined near the bottom
                                scope.cancel.$scope = sheetEl = null;
                                (done || angular.noop)();
                            });
                        };

                        scope.showSheet = function (done) {
                            if (scope.removed) return;

                            $document[0].body.appendChild(element[0]);
                            $document[0].body.classList.add('action-sheet-open');

                            $animate.addClass(element, 'active').then(function () {
                                if (scope.removed) return;
                                (done || angular.noop)();
                            });
                            $timeout(function () {
                                if (scope.removed) return;
                                sheetEl.addClass('action-sheet-up');
                            }, 20, false);
                        };

                        // registerBackButtonAction returns a callback to deregister the action
                        scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
                            scope.cancel,
                            300
                        );

                        scope.cancel = function () {
                            scope.removeSheet(opts.cancel);
                        };

                        scope.buttonClicked = function (index) {
                            if (opts.buttonClicked(index) === true) {
                                scope.removeSheet();
                            }
                        };

                        scope.showSheet();
                        scope.cancel.$scope = scope;

                        return scope.cancel;
                    }
                }])
            .directive('shareCombobox', ['$document', function ($document) {
                return {
                    restrict: 'E',
                    scope: true,
                    replace: true,
                    link: function ($scope, $element) {

                        var keyUp = function (e) {
                            if (e.which == 27) {
                                $scope.cancel();
                                $scope.$apply();
                            }
                        };

                        var backdropClick = function (e) {
                            if (e.target == $element[0]) {
                                $scope.cancel();
                                $scope.$apply();
                            }
                        };
                        $scope.$on('$destroy', function () {
                            $element.remove();
                            $document.unbind('keyup', keyUp);
                        });

                        $document.bind('keyup', keyUp);
                        $element.bind('click', backdropClick);
                    },
                    template: '<div class="action-sheet-backdrop">' +
                    '<div class="action-sheet-wrapper share-sheet">' +
                    '<div class="combobox-sheet">' +
                    '<div class="combobox-body">' +
                    '<ion-scroll class="combobox-content" scrollbar-y="false">' +
                    '<div>' +
                    '<div class="divShare"><img class="sharePng" src="img/icon_friendscircle.png" style="width:20%; height:20%;text-align: center;" ng-click="buttonClicked(1)" /></div>' +

                    '<div class="divShare"><img class="sharePng" src="img/icon_wechat.png" style="width:20%; height:20%;text-align: center;" ng-click="buttonClicked(0)"/></div>' +

                    '</div>' +
                    '</ion-scroll>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>'
                };
            }])
            .directive("ngTouchmove", function () {
                return {
                    controller: function ($scope, $element) {
                        $element.bind('touchstart', onTouchStart);
                        var startPosition, endPosition, deltaX;

                        function onTouchStart($event) {
                            var touch = $event.touches[0];
                            startPosition = {
                                x: touch.pageX,
                                y: touch.pageY
                            }
                            event.preventDefault();
                            if (touch.pageX == $event.changedTouches[0].pageX) {
                                endPosition = {
                                    x: touch.pageX,
                                    y: touch.pageY
                                }
                            }
                            $element.bind('touchmove', onTouchMove);
                            $element.bind('touchend', onTouchEnd);

                        };

                        function onTouchMove($event) {
                            var touch = $event.touches[0];
                            endPosition = {
                                x: touch.pageX,
                                y: touch.pageY
                            }
                        };

                        function onTouchEnd($event) {
                            deltaX = endPosition.x - startPosition.x;
                            //var method = '$scope.' + $element.attr('ng-touchmove');
                            $scope.$parent.someFunction(deltaX);
                            //$scope.$apply(function () {
                            //    eval(method);
                            //});
                            event.preventDefault();
                            $element.unbind('touchmove', onTouchMove);
                            $element.unbind('touchend', onTouchEnd);
                        };
                    }
                };
            })
            .controller('tabCtrl', function ($q, $scope, $http, shareCombobox, DataService) {
                $scope.someFunction = function (x) {
                    if (x > 0) {
                        $scope.back();
                    } else if (x < 0) {
                        $scope.advance();
                    }
                };
                $scope.data = {
                    activeType: 'SO'
                };
                var shareLineChart, sharePieChart;
                $scope.setActiveType = function (activeType) {
                    $scope.data.activeType = activeType;
                    DataService.setActiveType(activeType);
                    DataService.initData(DataService.getLocalTimer(activeType), activeType).then(function (data) {
                        var date = new Date();
                        DataService.setMs(date.getTime() - data.beginDate.getTime());
                        echarts(data.currentData);
                        DataService.setLocalTimer(activeType, data.time);
                    })
                };
                $scope.back = function () {
                    u9.showLoading();
                    var type = $scope.data.activeType;
                    DataService.refreshData(-1, DataService.getLocalTimer(type), type).then(function (data) {
                        var date = new Date();
                        DataService.setMs(date.getTime() - data.beginDate.getTime());
                        echarts(data.currentData);
                        DataService.setLocalTimer(type, data.time);
                    });
                };
                $scope.advance = function () {
                    u9.showLoading();
                    var type = $scope.data.activeType;
                    DataService.refreshData(1, DataService.getLocalTimer(type), type).then(function (data) {
                        var date = new Date();
                        DataService.setMs(date.getTime() - data.beginDate.getTime());
                        echarts(data.currentData);
                        //timer[type] = data.time;
                        DataService.setLocalTimer(type, data.time);
                    });
                };
                $scope.setActiveType('SO');
                function echarts(data) {
                    var linedom = document.getElementById('lineDom');
                    linedom.style.width = phoneWith + 'px';
                    linedom.style.height = (phoneHeight - 100) * 0.5 + 'px';
                    var lineChart = ec.init(linedom);

                    var piedom = document.getElementById('pieDom');
                    piedom.style.width = phoneWith + 'px';
                    piedom.style.height = (phoneHeight - 100) * 0.65 + 'px';
                    var pieChart = ec.init(piedom);
                    var lineSetOption = {
                        title: {
                            text: '金额趋势图',
                            x: 'left',
                            textStyle: {
                                fontWeight: 'normal'
                            }
                        },
                        tooltip: {
                            trigger: 'axis',
                            formatter: function (params) {
                                refreshPie(params[0]);
                                return params[0].name + ' <br/>' + params[0].value + '万元<br/>'
                            }
                        },
                        legend: {
                            data: (function () {
                                var res = [];
                                res.push(DataService.getName($scope.data.activeType).name);
                                return res;
                            })(),
                            x: 180
                        },
                        grid: {
                            y2: 35,
                            borderWidth: 0
                        },
                        calculable: false,
                        animation: true,
                        addDataAnimation: false,
                        animationDuration: 1000,
                        xAxis: [
                            {
                                type: 'category',
                                data: (function () {
                                    var res = [];
                                    var len = data.length;
                                    while (len--) {
                                        res.unshift(data[len].Year + '/' + data[len].Month);
                                    }
                                    return res;
                                })(),
                                boundaryGap: false
                            }
                        ],
                        yAxis: [
                            {
                                type: 'value',
                                name: '万元',
                                splitArea: {
                                    show: true,
                                    areaStyle: {
                                        color: ['rgba(255,255,255,0)', 'rgba(255,255,255,0)']
                                    }
                                },
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        width: 0.1
                                    }
                                }
                            }
                        ],
                        series: [
                            {
                                name: (function () {
                                    var res = DataService.getName($scope.data.activeType).name;
                                    return res;
                                })(),
                                type: 'line',
                                symbolSize: 5,
                                itemStyle: {
                                    normal: {
                                        color: 'rgba(53,204,249,1)',
                                        areaStyle: {
                                            type: 'default',
                                            color: 'rgba(53,204,249,0.5)'
                                        }
                                    },
                                    emphasis: {
                                        color: '#F9AB75'
                                    }
                                },
                                data: (function () {
                                    var res = [];
                                    var len = data.length;
                                    while (len--) {
                                        res.unshift(data[len].TotalMoney / 10000);
                                    }
                                    return res;
                                })()
                            }
                        ]
                    };
                    var pieSetOption = {
                        title: {
                            text: (function () {
                                var len = data.length;
                                var res = '产品分类(' + data[len - 1].Year + '/' + data[len - 1].Month + ')';
                                return res;
                            })(),
                            x: 'left',
                            textStyle: {
                                fontWeight: 'normal'
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c} ({d}%)"
                        },
                        legend: {
                            x: 'center',
                            y: 40,
                            data: (function () {
                                var res = [];
                                var len = data[data.length - 1].QueryDetailInfo.length;
                                var info = data[data.length - 1].QueryDetailInfo;
                                while (len--) {
                                    if (info[len].Money > 0) {
                                        res.push(info[len].SaleCategory == '' ? '其他' : info[len].SaleCategory);
                                    }
                                }
                                return res;
                            })()
                        },
                        animation: true,
                        noDataText: '本月没有销售额',
                        animationDuration: 1000,
                        series: [
                            {
                                name: (function () {
                                    return DataService.getName($scope.data.activeType).name;
                                })(),
                                type: 'pie',
                                radius: [50, 100],
                                avoidLabelOverlap: false,
                                center: ['50%', '64%'],
                                label: {
                                    normal: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        show: true,
                                        textStyle: {
                                            fontSize: '20',
                                            fontWeight: 'bold'
                                        }
                                    }
                                },
                                data: (function () {
                                    var res = [];
                                    var len = data[data.length - 1].QueryDetailInfo.length;
                                    var info = data[data.length - 1].QueryDetailInfo;
                                    while (len--) {
                                        if (info[len].Money > 0) {
                                            var dataInfo = {
                                                value: '',
                                                name: ''
                                            };
                                            dataInfo.value = info[len].Money / 10000;
                                            dataInfo.name = info[len].SaleCategory == '' ? '其他' : info[len].SaleCategory;
                                            res.push(dataInfo);
                                        }
                                    }
                                    return res;
                                })()
                            }
                        ]
                    };

                    function refreshPie(param) {
                        var id = param.dataIndex;
                        //DataService.setTitle($scope.data.activeType, param.name);
                        //pieSetOption.title.text = DataService.getTitle($scope.data.activeType);
                        pieSetOption.title.text = '产品分类(' + param.name + ')';
                        pieSetOption.legend.data = (function () {
                            var res = [];
                            var len = data[id].QueryDetailInfo.length;
                            var info = data[id].QueryDetailInfo;
                            while (len--) {
                                if (info[len].Money > 0) {
                                    res.push(info[len].SaleCategory == '' ? '其他' : info[len].SaleCategory);
                                }
                            }
                            return res;
                        })();
                        pieSetOption.series[0].data = (function () {
                            var res = [];
                            var len = data[id].QueryDetailInfo.length;
                            var info = data[id].QueryDetailInfo;
                            while (len--) {
                                if (info[len].Money > 0) {
                                    var dataInfo = {
                                        value: '',
                                        name: ''
                                    };
                                    dataInfo.value = info[len].Money / 10000;
                                    dataInfo.name = info[len].SaleCategory == '' ? '其他' : info[len].SaleCategory;
                                    res.push(dataInfo);
                                }
                            }
                            return res;
                        })();
                        pieChart.clear();
                        if (pieSetOption.series[0].data.length > 0) {
                            pieChart.hideLoading();
                        }
                        pieChart.setOption(pieSetOption);
                    }

                    lineChart.clear();
                    lineChart.setOption(lineSetOption);
                    shareLineChart = lineChart;

                    pieChart.clear();
                    pieChart.setOption(pieSetOption);
                    sharePieChart = pieChart;
                    setTimeout(function () {
                        u9.hideLoading();
                    }, DataService.getMs() + 1000);

                }

                $scope.shareChartImage = function () {
                    var imgLine = document.createElement("img");
                    imgLine.src = shareLineChart.getDataURL("png");
                    var c = document.getElementById("myCanvas");
                    c.width = phoneWith;
                    c.height = phoneHeight - 100;
                    var ctx = c.getContext("2d");
                    ctx.fillStyle = "white";
                    ctx.fillRect(0, 0, phoneWith, phoneHeight - 100);
                    imgLine.onload = function () {
                        ctx.drawImage(imgLine, 0, 0, imgLine.width, imgLine.height, 20, 10, c.width * 0.9, c.height * 0.4);
                        var imgPie = document.createElement("img");
                        imgPie.src = sharePieChart.getDataURL("png");
                        imgPie.onload = function () {
                            ctx.drawImage(imgPie, 0, 0, imgPie.width, imgPie.height, 20, c.height * 0.4 + 10, c.width * 0.9, c.height * 0.55);
                            var u = navigator.userAgent;
                            if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
                                parent.window.plugins.socialsharing.share('分享', null, c.toDataURL("image/png"), null);
                            } else if (u.indexOf('iPhone') > -1) {//苹果手机
                                shareCombobox.show({
                                    buttonClicked: function (index) {
                                        shareWeChat(c.toDataURL("image/png"), index, function () {
                                            //alert("分享成功");
                                        }, function (reason) {
                                            //alert(reason);
                                        });
                                        return true;
                                    }
                                });
                            }
                        };
                    };
                };
                function shareWeChat(uri, index, successCallback, failCallback) {
                    parent.window.Wechat.setOptions({
                        appId: 'wx75e363993c0f2683'
                    });
                    var params = {
                        "scene": 1,
                        "message": {
                            "title": "[TEST]send-photo",
                            "description": "[TEST]Sending from test application",
                            "thumb": uri,
                            "mediaTagName": "TEST-TAG-001",
                            "messageExt": "这是第三方带的测试字段",
                            "messageAction": "<action>dotalist</action>",
                            "media": {
                                type: 4,
                                image: uri
                            }
                        }
                    };
                    params.scene = index;
                    parent.window.Wechat.share(params, function () {
                        successCallback();
                    }, function (reason) {
                        if (reason == '参数错误') {
                            u9.alert('图片太大，微信接口限制大小，请截屏分享！');
                        }
                        failCallback(reason)
                    });

                }
            })
            .run(function ($ionicPlatform) {
                $ionicPlatform.ready(function () {

                    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    }
                    if (window.StatusBar) {
                        StatusBar.styleLightContent();
                    }
                });
            });
        angular.bootstrap(document, ['starter']);
    })
})
;
